package cn.kingyea.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.HashMap;

import parquet.org.slf4j.Logger;
import parquet.org.slf4j.LoggerFactory;

public class ApacheHiveUtils {
	private static final String HIVE_DRIVER = "org.apache.hive.jdbc.HiveDriver";
	private static Logger LOG = LoggerFactory.getLogger(ApacheHiveUtils.class);
	private static Connection connection = null;

	
	private static Connection getConnection() {
		try {
			synchronized (HiveUtils.class) {
				if (null != connection) {
					return connection;
				} else {
					Class.forName(HIVE_DRIVER);
					connection = DriverManager.getConnection("jdbc:hive2://192.168.137.51:10000", "root", "");
				}
			}
			return connection;
		} catch (Exception e) {
			LOG.info(e.getMessage());
		}
		return null;
	}

	public static Object executeQuery(String sql) {
		try {
			PreparedStatement ps = getConnection().prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			ResultSetMetaData meta = rs.getMetaData();
			int columnCount = meta.getColumnCount();
			HashMap<String, String> map = new HashMap<String, String>();
			while (rs.next()) {
				for (int i = 1; i <= columnCount; i++) {
					String lableName = meta.getColumnLabel(i);
					map.put(lableName.toLowerCase(), rs.getString(i));
				}
			}
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			LOG.info(e.getMessage());
		}
		return null;
	}

	public static Object executeUpdate(String sql) {
		try {
			if(null != sql && sql.contains("drop")){
//				return null;//。。
			}
			Connection connection2 = getConnection();
			
			PreparedStatement ps = connection2.prepareStatement(sql);
			boolean rs = ps.execute();
			return rs;
		} catch (Exception e) {
			e.printStackTrace();
			LOG.info(e.getMessage());
		}
		return null;
	}
}
